package org.yaac.server.egql.evaluator.aggregator;

import java.math.BigDecimal;

import org.yaac.server.egql.evaluator.EvaluationResult;

/**
 * count must use BigDecimal instead of Long
 * 
 * because in having clause, number is evaluated as BigDecimal
 * 
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class CountAggregator implements Aggregator {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private BigDecimal count;
	
	public CountAggregator() {
		count = BigDecimal.ZERO;
	}

	@Override
	public void aggregate(EvaluationResult delta) {
		if (delta.getPayload() != null) {
			count = count.add(BigDecimal.ONE);
		}
	}

	@Override
	public String asString() {
		return count.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((count == null) ? 0 : count.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CountAggregator other = (CountAggregator) obj;
		if (count == null) {
			if (other.count != null)
				return false;
		} else if (!count.equals(other.count))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "CountAggregator [count=" + count + "]";
	}

	@Override
	public BigDecimal getResult() {
		return count;
	}
}
